<template>
  <li>
    <p>
      {{ data.name }}
      <button v-if="hasChildren" @click="show = !show">
        [{{ show ? "-" : "+" }}]
      </button>
    </p>

    <ul v-if="hasChildren && show">
      <!-- 递归调用本身 -->
      <TreeItem v-for="item in data.children" :data="item" />
    </ul>
  </li>
</template>

<script>
export default {
  name: "TreeItem",

  props: {
    /**
     * {
     *    name: '',
     *    ?children: []
     * }
     */
    data: {
      type: Object,
      required: true,
    },
  },

  data() {
    return {
      show: false, // 用于控制是否显示子级
    };
  },

  computed: {
    // 是否有子级
    hasChildren() {
      return this.data.children && this.data.children.length > 0;
    },
  },
};
</script>
